package com.huanf.utils;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author: 35238
 * 功能:
 * 时间: 2023-11-12 23:39
 */
@Component
public class MyHttpUtil {

    @Value("${pa.downloadPath}")
    private String path;

    //创建连接池
    private PoolingHttpClientConnectionManager xxpool;
    public MyHttpUtil() {
        this.xxpool = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        xxpool.setMaxTotal(100);
        //设置每个主机的最大连接数
        xxpool.setDefaultMaxPerRoute(10);
    }

    /**
     * 根据请求地址，下载页面的html数据
     * @param xxurl 网址地址
     * @return string html数据
     */
    public String xxGetHtml(String xxurl) {
        //获取HttpClient对象
        CloseableHttpClient xxhttpClient = HttpClients.custom().setConnectionManager(xxpool).build();

        //创建xxGetHtml的对象
        HttpGet xxhttpGet = new HttpGet(xxurl);

        //设置请求信息
        xxhttpGet.setConfig(xxgetConfig());

        //具体操作
        CloseableHttpResponse xxresponse = null;
        try {
            //使用HttpClient发起请求，获取响应
            xxresponse = xxhttpClient.execute(xxhttpGet);
            //如果响应成功，那么就继续
            if (xxresponse.getStatusLine().getStatusCode() == 200) {
                //如果响应体不为空，那么就解析响应并返回结果
                if (xxresponse.getEntity() != null) {
                    String result = EntityUtils.toString(xxresponse.getEntity(), "utf8");
                    return result;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(xxresponse != null) {
                try {
                    xxresponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "您请求的网站拒绝了连接";
    }



    /**
     * 根据请求地址，下载页面的图片数据
     * @param yyurl 图片地址
     * @return string 图片名称
     */
    public String xxGetImage(String yyurl) {
        CloseableHttpClient xxhttpClient = HttpClients.custom().setConnectionManager(xxpool).build();
        HttpGet xxhttpGet = new HttpGet(yyurl);
        xxhttpGet.setConfig(xxgetConfig());
        CloseableHttpResponse xxresponse = null;
        try {
            xxresponse = xxhttpClient.execute(xxhttpGet);
            if (xxresponse.getStatusLine().getStatusCode() == 200) {
                if (xxresponse.getEntity() != null) {
                    //获取图片的后缀，截取小数点后的url名，例如.jpg
                    String afterFix = yyurl.substring(yyurl.lastIndexOf("."));
                    //重命名图片，也就是自定义图片名称
                    String picName = UUID.randomUUID().toString() + afterFix;
                    //把网页的图片下载到本地电脑。例如存放到指定(在yml里面指定)目录下
                    OutputStream outputStream = new FileOutputStream(new File(path+picName));
                    xxresponse.getEntity().writeTo(outputStream);
                    //返回图片名称
                    return picName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(xxresponse != null) {
                try {
                    xxresponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "您请求的网站拒绝了连接";
    }

    //设置请求的信息
    private RequestConfig xxgetConfig() {
        RequestConfig yyconfig = RequestConfig.custom()
                .setConnectTimeout(1000) //创建连接的最长时间
                .setConnectionRequestTimeout(500) //获取连接的最长时间
                .setSocketTimeout(10000) //数据传输的最长时间
                .build();
        return yyconfig;
    }
}
